package util

import (
	"context"
	"fmt"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api"
	"github.com/influxdata/influxdb-client-go/v2/api/query"
	"seven-admin/core/config"
	"time"
)

var InfluxDBUtil = func() *influxDBUtil {
	return &influxDBUtil{
		db: influxdb2.NewClient(config.Env.INFLUXDB_URL, config.Env.INFLUXDB_TOKEN),
	}
}

type influxDBUtil struct {
	db influxdb2.Client
}

func (i *influxDBUtil) GetDB() influxdb2.Client {
	return i.db
}

func (i *influxDBUtil) Close() {
	i.db.Close()
}

func (i *influxDBUtil) GetWriteAPI() api.WriteAPI {
	return i.db.WriteAPI(config.Env.INFLUXDB_ORGANIZATION, config.Env.INFLUXDB_BUCKET)
}

func (i *influxDBUtil) GetQueryAPI() api.QueryAPI {
	return i.db.QueryAPI(config.Env.INFLUXDB_ORGANIZATION)
}

// Query 查询原始数据
func (i *influxDBUtil) Query(query string) (*query.FluxRecord, error) {
	obj := i.GetQueryAPI()
	result, err := obj.Query(context.Background(), query)
	if err != nil {
		return nil, err
	}
	defer result.Close()
	for result.Next() {
		return result.Record(), nil
	}
	err = result.Err()
	if err != nil {
		fmt.Printf("query response error: %v\n", err)
		return nil, err
	}
	return nil, err
}

// Write 写入数据
func (i *influxDBUtil) Write(measurement string, tags map[string]string, fields map[string]interface{}) {
	writeAPI := i.GetWriteAPI()
	p := influxdb2.NewPoint(measurement, tags, fields, time.Now())
	writeAPI.WritePoint(p)
}
func (i *influxDBUtil) Flush() {
	writeAPI := i.GetWriteAPI()
	writeAPI.Flush()
}
